/*
 * Copyright 2013 Aliyun.com All right reserved. This software is the
 * confidential and proprietary information of Aliyun.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Aliyun.com .
 */
package com.mtauto.action.device;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.codeanywhere.easyRestful.base.RequestContext;
import org.codeanywhere.easyRestful.base.annotation.Request;
import org.codeanywhere.easyRestful.base.annotation.SpringBean;

import com.mtauto.exception.MtautoException;
import com.mtauto.model.Apk;
import com.mtauto.model.Result;
import com.mtauto.service.AdbService;
import com.mtauto.service.ApkService;

/**
 * @author <a href="mailto:li.jinl@alibaba-inc.com">Stone.J</a> Nov 21, 2013
 */
public class Uninstall {

    @Request
    private RequestContext rc;
    @SpringBean
    private AdbService     adbService;
    @SpringBean
    private ApkService     apkService;

    public void execute() {
        String serialno = rc.getHttpServletRequest().getParameter("serialno");
        if (serialno == null || serialno.isEmpty()) {
            rc.put("result", Result.createFailResult("illegal arguments[serialno is null]."));
            return;
        }

        String[] serialnos = adbService.getSerialnos();
        if (!ArrayUtils.contains(serialnos, serialno)) {
            rc.put("result", Result.createFailResult("illegal arguments[device not found.]."));
            return;
        }

        List<Result<String>> data = new ArrayList<Result<String>>();
        Collection<Apk> apks = apkService.getApks();
        String[] pkgs = adbService.getPackages(serialno);
        for (Apk apk : apks) {
            if (!ArrayUtils.contains(pkgs, apk.getName())) {
                continue;
            }

            boolean flag;
            try {
                flag = adbService.uninstall(serialno, apk.getName());
            } catch (MtautoException e) {
                flag = false;
            }
            Result<String> r = new Result<String>();
            r.setSuccess(flag);
            r.setData(apk.getTitle());
            data.add(r);
        }
        rc.put("result", Result.createResult(data));
    }
}
